import * as echarts from '../../../components/echarts/echarts';
const app = getApp();
const requestUtil = require("../../../utils/request");
const util = require("../../../utils/util");
const api = require("../../../config/api");
Page({
    /**
     * 页面的初始数据
     */
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        tableNoDataMsg: '暂无数据~',
        fyNum: 1,
        fySize: 10,
        dataList: [],
        ToolTabCur: 2,
        qIndex: 0,
        uIndex: 0,
        dIndex: 0,
        toolbars:[
            {name:"写汇报", class:"cuIcon-post", url: "/pages/question/center/center"},
            {name:"看汇报", class:"cuIcon-punch", url: "/pages/question/list/answerList"},
            {name:"统计", class:"cuIcon-crown", url: "/pages/question/total/questionTotal"},
            {name:"我的", class:"cuIcon-profile", url: "/pages/question/my/myQuestionList"},
        ],
        betDateName: null,
        dList: [
            {id: 0, name: '本月'},
            {id: 1, name:'本周'},
            {id: 2, name:'上周'},
            {id: 3, name:'上月'},
            {id: 4, name:'自定义区间'},
        ],
        uList: [],
        selectUser: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.formatData();
        this.questionList();
    },
    formatData(){
        let dList = this.data.dList;
        var date = new Date();
        var year = date.getFullYear();//本年
        var month = date.getMonth();//本月
        var week = date.getDay();//当前星期 0.1.2.3.4.5.6[0=周日]
        var time = date.getTime();//当天
        var oneDayTime = 24 * 60 * 60 * 1000;//一天的总ms

        //本月
        dList[0].startDate = util.dateFormat(date, 'yyyy-MM') + '-01';
        dList[0].endDate = util.dateFormat(date, 'yyyy-MM') + '-' + new Date(year, month+1, 0).getDate();

        //本周
        var thisWeekFirst = (1 - week) * oneDayTime + time;
        var thisWeekLast = thisWeekFirst + 6 * oneDayTime;
        dList[1].startDate = util.dateFormat(new Date(thisWeekFirst), 'yyyy-MM-dd');
        dList[1].endDate = util.dateFormat(new Date(thisWeekLast), 'yyyy-MM-dd');

        //上周
        dList[2].startDate = util.dateFormat(new Date(thisWeekFirst - 7*oneDayTime), 'yyyy-MM-dd');
        dList[2].endDate = util.dateFormat(new Date(thisWeekFirst - oneDayTime), 'yyyy-MM-dd');

        //上月
        var preDate = new Date(year, month, 0);
        var lastDay = preDate.getDate();
        dList[3].startDate = util.dateFormat(preDate, 'yyyy-MM')  + '-01';
        dList[3].endDate = util.dateFormat(preDate, 'yyyy-MM') + '-' + lastDay;

        dList[4].startDate = util.dateFormat(date,'yyyy-MM-dd');
        dList[4].endDate = util.dateFormat(date,'yyyy-MM-dd');
        this.setData({
            dList: dList,
        })
    },
    async questionList(){
        let that = this;
        let res = await requestUtil.request("POST", api.urls.questionList, {
            companyId: app.globalData.employeeInfo.companyId,
            userIds: app.globalData.employeeInfo.isAdmin == 0 ? app.globalData.employeeInfo.id : null,
        })
        let qList = [];
        for(var i in res.data.data) {
            qList.push({id: res.data.data[i].id, name: res.data.data[i].questionName, type: res.data.data[i].questionType});
        }
        that.setData({
            qList: qList,
            questionList: res.data.data
        })
        this.answerTotal();
        this.userList(qList[0].type == 2 ? qList[0].id : 0);
        this.answerYmTotal();
    },
    async answerTotal(){
        let that = this;
        let qInfo = that.data.questionList[that.data.qIndex];
        let res = await requestUtil.request("POST", api.urls.answerTotal, {
            questionId: qInfo.id,
            startDate: that.data.dList[that.data.dIndex].startDate,
            endDate: that.data.dList[that.data.dIndex].endDate
        })
        let ultotal = res.data.data;
        let utotal = {total: 0, finished: 0};;
        for(let i in ultotal) {
            ultotal[i]['nofinished'] = ultotal[i].total - ultotal[i].finished;
            if(!that.data.selectUser) {
                utotal['total'] += ultotal[i].total;
                utotal['finished'] += ultotal[i].finished;
            }else if(that.data.selectUser == ultotal[i].userName) {
                utotal = ultotal[i];
            }
        }
        let answerTableHeader = [{
            prop: 'userName',
            width: 150,
            label: '员工姓名',
          }, {
            prop: 'total',
            width: 120,
            label: '总计'
          }, {
            prop: 'finished',
            width: 120,
            label: '已完成'
          }, {
            prop: 'nofinished',
            width: 120,
            label: '未完成'
          } ];
        let questionContent = JSON.parse(qInfo.questionContent);
        let wData = questionContent["wData"];
        for(let i in wData) {
            if('radio,checkbox'.includes(wData[i].type)) {
                let options = wData[i].option;
                let item = {
                    prop: wData[i].title,
                    width: 150 * options.length,
                    label: wData[i].title + "（%）"
                }
                item.children = [];
                for(var j in options) {
                    item.children[j] = {
                        prop: wData[i].title + '-' + options[j],
                        width: 150,
                        label: options[j]
                    }
                }
                answerTableHeader.push(item);
            }
        }
        for(let i in ultotal) {
            if(!ultotal[i].formatData) continue;
            let list = JSON.parse(ultotal[i].formatData);
            for(let j in list) {
                ultotal[i][list[j].key] = list[j].value;
            }
        }
        that.setData({
            utotal: utotal,
            ultotal: ultotal,
            answerTableHeader: answerTableHeader,
        })
        let ecTotal = this.selectComponent('#ecTotal');
        ecTotal.init((canvas, width, height, dpr) => {
            const lineChart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr // new
            });
            lineChart.setOption(ecTotalOption(that.data));
            return lineChart;
        })
    },
    async answerYmTotal(){
        let that = this;
        var today = new Date() //当天
        today.setMonth(today.getMonth()-5)
        let startDate = util.dateFormat(today, 'yyyy-MM');
        let res = await requestUtil.request("POST", api.urls.answerYmTotal, {
            questionId: that.data.qList[that.data.qIndex].id,
            startDate: startDate,
            userName: that.data.selectUser
        })
        let ymtotal = res.data.data;
        that.setData({
            ymtotal: ymtotal,
        })
        let ecMonthTotal = this.selectComponent('#ecMonthTotal');
        ecMonthTotal.init((canvas, width, height, dpr) => {
            const lineChart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr // new
            });
            lineChart.setOption(ecMonthTotalOption(that.data));
            return lineChart;
        })
    },
    async userList(qId){
        if(qId == 0) {
            this.setData({
                uList: [],
                selectUser: '',
            })
            return;
        }
        let that = this;
        let res = await requestUtil.request("GET", api.urls.questionUserList, {questionId: qId});
        that.setData({
            uList: res.data.data,
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        console.log("上拉粗蒂")
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        
    },
    toolTabSelect(e){
        let index = e.currentTarget.dataset.index;
        wx:wx.navigateTo({
          url: this.data.toolbars[index].url
        })
    },
    toRedic(e) {
        let id = e.currentTarget.dataset.id;
        wx:wx.navigateTo({
          url: "/pages/question/questionDetail/questionDetail?answerId=" + id,
        })
    },
    showModal(e) {
        this.setData({
          modalName: e.currentTarget.dataset.target
        })
    },
    hideModal(e) {
        this.setData({
          modalName: null
        })
    },
    questionPickerChange(e) {
        let idx = parseInt(e.detail.value);
        if(this.data.qIndex == idx) return;
        this.setData({
          qIndex: idx
        })
        let qitem = this.data.qList[idx];
        this.userList(qitem.type == 2 ? qitem.id : 0);
        if(qitem.type == 2) {
            this.answerTotal();
            this.answerYmTotal();
        }
    },
    datePickerChange(e) {
        let idx = parseInt(e.detail.value);
        if(idx == 4) {
            this.setData({
                modalName: 'zdyDate'
            })
            return;
        }
        if(this.data.dIndex == idx) return;
        this.setData({
          dIndex: idx,
          betDateName: null,
        })
        this.answerTotal();
        this.answerYmTotal();
    },
    changeSelectUser(e) {
        let name = e.detail.value;
        if(this.data.selectUser == name) return;
        this.hideModal();
        this.setData({
            selectUser: name
        })
        this.answerTotal();
        this.answerYmTotal();
    },
    zdyDateChange(e) {
        let name = e.currentTarget.dataset.name;
        let dList = this.data.dList;
        dList[4][name] = e.detail.value;
        this.setData({
            dList: dList,
        })
    },
    sureZdyDate(e) {
        let dList = this.data.dList;
        let startStr = util.dateFormat(new Date(dList[4].startDate), 'yy/M/d');
        let endStr = util.dateFormat(new Date(dList[4].endDate),'yy/M/d');
        this.setData({
            modalName: null,
            betDateName: startStr + "-" + endStr,
            dIndex: 4
        })
        this.answerTotal();
        this.answerYmTotal();
    },
    onRowClick: function (e) {
        let rowData = e.detail.currentTarget.dataset.it; // 行数据
        let userName = rowData.userName;
        let questionId = this.data.qList[this.data.qIndex].id;
        let dIndex = this.data.dIndex;
        let startDate = this.data.dList[this.data.dIndex].startDate;
        let endDate = this.data.dList[this.data.dIndex].endDate;
        wx.navigateTo({
          url: '/pages/question/userItem/userItem?userName=' + userName + '&questionId=' + questionId + '&dIndex=' + dIndex + '&startDate=' + startDate + '&endDate=' + endDate
        })
    }
})

function ecTotalOption(data) {
    return {
        title: {
            text: '',
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['总计','已完成','未完成']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
        },
        yAxis: {
            type: 'category',
            data: [data.selectUser ? data.selectUser : '所有员工']
        },
        series: [
            {
                name: '总计',
                type: 'bar',
                label: {
                    show: true
                },
                data: [data.utotal['total']]
            },
            {
                name: '已完成',
                type: 'bar',
                label: {
                    show: true
                },
                data: [data.utotal['finished']]
            },
            {
                name: '未完成',
                type: 'bar',
                label: {
                    show: true
                },
                data: [data.utotal['total'] - data.utotal['finished']]
            }
        ]
    };	
}

function ecMonthTotalOption(data) {
    return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {},
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: (function(){
                var result = [];
                for(var i in data.ymtotal) {
                    result.push(data.ymtotal[i].ym)
                }
                return result;
            })(),
            axisLabel: {
                interval: 0, 
                rotate: 80
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '总计',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            label: {
              show: true,
              position: 'top'
            },
            data: (function(){
                var result = [];
                for(var i in data.ymtotal) {
                    result.push(data.ymtotal[i].total)
                }
                return result;
            })()
          },
          {
            name: '已完成',
            type: 'bar',
            stack: 'Ad',
            emphasis: {
              focus: 'series'
            },
            label: {
              show: true,
              position: 'top'
            },
            data:  (function(){
                var result = [];
                for(var i in data.ymtotal) {
                    result.push(data.ymtotal[i].finished)
                }
                return result;
            })()
          }
        ]
      };
}